package cn.aiseminar.aisinterphone;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private TabHost mMainTabHost = null;
	private TabSpec friendListSpec = null;
	private TabSpec chatListSpec = null;
	private TabSpec scanListSpec = null;
	
	private ListView mFriendListView = null;
	private ListView mChatListView = null;
	private ListView mScanListView = null;
	
	private BluetoothAdapter mBTAdapter = null;
	private BluetoothPhoneService mBTService = null;
	
	private DeviceAdapter mFriendListArrayAdapter = null;
	private DeviceAdapter mChatListArrayAdapter = null;
	private DeviceAdapter mNewDeviceArrayAdapter = null;
	
	private BroadcastReceiver mReceiver = null;
	@SuppressLint("HandlerLeak")
	private final Handler mMessageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what)
			{
			case BluetoothPhoneService.MSG_REMOTE_DEVICE_CONNECTED:
//				Intent talkIntent = new Intent(MainActivity.this, MessageActivity.class);
//				startActivity(talkIntent);
				Intent voiceIntent = new Intent(MainActivity.this, VoiceActivity.class);
				startActivity(voiceIntent);
				break;
			}
			super.handleMessage(msg);
		}
	};
		
	private static final int REQUEST_ENABLE_BT = 1;
//	private static final int REQUEST_CONNECT_DEVICE = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mBTAdapter = BluetoothAdapter.getDefaultAdapter();
		if (null == mBTAdapter)
		{
			Toast.makeText(this, R.string.msg_no_bluetooth, Toast.LENGTH_LONG).show();
			this.finish();
			return;
		}
		
		mMainTabHost = (TabHost)this.findViewById(android.R.id.tabhost);
		mMainTabHost.setup();
		
		friendListSpec = mMainTabHost.newTabSpec("FriendList");
		friendListSpec.setIndicator(this.getString(R.string.menu_friends));
		friendListSpec.setContent(R.id.tabFriend);
		mMainTabHost.addTab(friendListSpec);
		
		mFriendListView = (ListView)this.findViewById(R.id.listViewFriends);
		mFriendListArrayAdapter = new DeviceAdapter(this, null);
		mFriendListView.setAdapter(mFriendListArrayAdapter);
				
		chatListSpec = mMainTabHost.newTabSpec("ChatList");
		chatListSpec.setIndicator(this.getString(R.string.menu_chat));
		chatListSpec.setContent(R.id.tabChat);
		mMainTabHost.addTab(chatListSpec);
		
		mChatListView = (ListView)this.findViewById(R.id.listViewChats);
		mChatListArrayAdapter = new DeviceAdapter(this, null);
		mChatListView.setAdapter(mChatListArrayAdapter);
		
		scanListSpec = mMainTabHost.newTabSpec("ScanList");
		scanListSpec.setIndicator(this.getString(R.string.menu_scan));
		scanListSpec.setContent(R.id.tabScan);
		mMainTabHost.addTab(scanListSpec);
		
		mScanListView = (ListView)this.findViewById(R.id.listViewScan);
		mNewDeviceArrayAdapter = new DeviceAdapter(this, null);
		mScanListView.setAdapter(mNewDeviceArrayAdapter);
		
		mMainTabHost.setOnTabChangedListener(new OnTabChangeListener() {
					public void  onTabChanged(String tabId)
					{
						setupPhoneService();
					}
				});
		
		
		OnItemClickListener connectDeviceListener = new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				if (null != mBTService)
				{
					Device dev = (Device)mFriendListArrayAdapter.getItem(position);
//					startTalkingWithDevice(dev);
					startVoiceTalkingWithDevice(dev);
				}	
			}
		};
		
		mFriendListView.setOnItemClickListener(connectDeviceListener);
		mScanListView.setOnItemClickListener(connectDeviceListener);
				
		mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (BluetoothDevice.ACTION_FOUND.equals(action))
				{
					BluetoothDevice btDev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
					Device dev = new Device();
					dev.setName(btDev.getName());
					dev.setMacAddress(btDev.getAddress());
					mNewDeviceArrayAdapter.addDevice(dev);
				}
			}
		};
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		this.registerReceiver(mReceiver, filter);
	}

	@Override
	protected void onStart() {
		super.onStart();
		
		if (! mBTAdapter.isEnabled())
		{
			Intent btEnableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			this.startActivityForResult(btEnableIntent, REQUEST_ENABLE_BT);
		}
		else
		{
			setupPhoneService();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch(requestCode)
		{
			case REQUEST_ENABLE_BT:
			{
				if (resultCode == Activity.RESULT_OK)
				{
					setupPhoneService();
				}
				else
				{
					Toast.makeText(this, R.string.msg_no_bluetooth, Toast.LENGTH_LONG).show();
					this.finish();
				}
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		this.unregisterReceiver(mReceiver);
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	private void setupPhoneService() {
		if (null == mBTService)
		{
			mBTService = BluetoothPhoneService.getBluetoothPhoneService();
		}
		
		mBTService.setMsgHandler(mMessageHandler);
		mBTService.startAcceptServer();
		
		String tabId = mMainTabHost.getCurrentTabTag();
		if (tabId.equals(friendListSpec.getTag()))
		{
			mFriendListArrayAdapter.setDeviceData(mBTService.getPairedDeviceList());
		}
		else if (tabId.equals(chatListSpec.getTag()))
		{
			
		}
		else if (tabId.equals(scanListSpec.getTag()))
		{
			mNewDeviceArrayAdapter.setDeviceData(null);
			mBTService.startDiscovery();
			
			// make self discoverable
//			Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//			discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 240);
//			startActivity(discoverableIntent);
//			Toast.makeText(this, R.string.msg_bluetooth_discoverable, Toast.LENGTH_LONG).show();
		}
	}
	
	public void startTalkingWithDevice(Device dev)
	{
		mBTService.cancelDiscovery();
		mBTService.connectDevice(dev.getMacAddress());
		Intent talkIntent = new Intent(MainActivity.this, MessageActivity.class);
		startActivity(talkIntent);
	}
	
	public void startVoiceTalkingWithDevice(Device dev)
	{
		mBTService.cancelDiscovery();
		mBTService.connectDevice(dev.getMacAddress());
		Intent talkIntent = new Intent(MainActivity.this, VoiceActivity.class);
		startActivity(talkIntent);
	}
}
